﻿using LJ.Socket.Data;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LJ.Socket.Server.StraightChicken.Internal;

public class SocketServerHandlerInvoker(IServiceScopeFactory serviceScopeFactory, ISocketServerHandlerManager socketServerHandlerManager) : ISocketServerHandlerInvoker
{
    private readonly IServiceScopeFactory _serviceScopeFactory = serviceScopeFactory;
    private readonly ISocketServerHandlerManager _socketServerHandlerManager = socketServerHandlerManager;

    public async Task InvokeAsync(SocketMessage message)
    {
        var socketServerHandlerDescriptor = _socketServerHandlerManager.GetSocketServerHandlerDescriptor(message.GetName());

        using var scope = _serviceScopeFactory.CreateScope();
        var eventHandlerInstance =
            scope.ServiceProvider.GetRequiredService(socketServerHandlerDescriptor.SocketServerHandlerType);

        var method = socketServerHandlerDescriptor.SocketServerHandlerType.GetMethod("ExecuteAsync",
                [socketServerHandlerDescriptor.SocketDataType, typeof(IDictionary<string, string>)]);

        var task = (Task?)method!.Invoke(eventHandlerInstance, [message.Value, message.Headers]);
        await task!.ConfigureAwait(false);
    }
}
